{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table class=\"ee-notebook-buttons\" align=\"left\">\n",
    "    <td><a target=\"_blank\"  href=\"https://github.com/giswqs/geemap/tree/master/tutorials/Image/09_edge_detection.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n",
    "    <td><a target=\"_blank\"  href=\"https://nbviewer.jupyter.org/github/giswqs/geemap/blob/master/tutorials/Image/09_edge_detection.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n",
    "    <td><a target=\"_blank\"  href=\"https://colab.research.google.com/github/giswqs/geemap/blob/master/tutorials/Image/09_edge_detection.ipynb\"><img width=26px src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Edge detection\n",
    "[Edge detection](http://en.wikipedia.org/wiki/Edge_detection) is applicable to a wide range of image processing tasks. In addition to the edge detection kernels described in the [convolutions section](https://developers.google.com/earth-engine/image_convolutions.html), there are several specialized edge detection algorithms in Earth Engine. The Canny edge detection algorithm ([Canny 1986](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4767851)) uses four separate filters to identify the diagonal, vertical, and horizontal edges. The calculation extracts the first derivative value for the horizontal and vertical directions and computes the gradient magnitude. Gradients of smaller magnitude are suppressed. To eliminate high-frequency noise, optionally pre-filter the image with a Gaussian kernel. For example:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Install Earth Engine API and geemap\n",
    "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n",
    "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n",
    "\n",
    "**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Installs geemap package\n",
    "import subprocess\n",
    "\n",
    "try:\n",
    "    import geemap\n",
    "except ImportError:\n",
    "    print('geemap package not installed. Installing ...')\n",
    "    subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n",
    "\n",
    "# Checks whether this notebook is running on Google Colab\n",
    "try:\n",
    "    import google.colab\n",
    "    import geemap.eefolium as emap\n",
    "except:\n",
    "    import geemap as emap\n",
    "\n",
    "# Authenticates and initializes Earth Engine\n",
    "import ee\n",
    "\n",
    "try:\n",
    "    ee.Initialize()\n",
    "except Exception as e:\n",
    "    ee.Authenticate()\n",
    "    ee.Initialize()  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create an interactive map \n",
    "The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = emap.Map(center=[40,-100], zoom=4)\n",
    "Map.add_basemap('ROADMAP') # Add Google Map\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add Earth Engine Python script "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load a Landsat 8 image, select the panchromatic band.\n",
    "image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').select('B8')\n",
    "\n",
    "# Perform Canny edge detection and display the result.\n",
    "canny = ee.Algorithms.CannyEdgeDetector(**{\n",
    "  'image': image, 'threshold': 10, 'sigma': 1\n",
    "})\n",
    "Map.setCenter(-122.054, 37.7295, 10)\n",
    "Map.addLayer(canny, {}, 'canny')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the `threshold` parameter determines the minimum gradient magnitude and the `sigma` parameter is the standard deviation (SD) of a Gaussian pre-filter to remove high-frequency noise. For line extraction from an edge detector, Earth Engine implements the Hough transform ([Duda and Hart 1972](http://dl.acm.org/citation.cfm?id=361242)). Continuing the previous example, extract lines from the Canny detector with:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Perform Hough transform of the Canny result and display.\n",
    "hough = ee.Algorithms.HoughTransform(canny, 256, 600, 100)\n",
    "Map.addLayer(hough, {}, 'hough')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another specialized algorithm in Earth Engine is `zeroCrossing()`. A zero-crossing is defined as any pixel where the right, bottom, or diagonal bottom-right pixel has the opposite sign. If any of these pixels is of opposite sign, the current pixel is set to 1 (zero-crossing); otherwise it's set to zero. To detect edges, the zero-crossings algorithm can be applied to an estimate of the image second derivative. The following demonstrates using `zeroCrossing()` for edge detection:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load a Landsat 8 image, select the panchromatic band.\n",
    "image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').select('B8')\n",
    "Map.addLayer(image, {'max': 12000})\n",
    "\n",
    "# Define a \"fat\" Gaussian kernel.\n",
    "fat = ee.Kernel.gaussian(**{\n",
    "  'radius': 3,\n",
    "  'sigma': 3,\n",
    "  'units': 'pixels',\n",
    "  'normalize': True,\n",
    "  'magnitude': -1\n",
    "})\n",
    "\n",
    "# Define a \"skinny\" Gaussian kernel.\n",
    "skinny = ee.Kernel.gaussian(**{\n",
    "  'radius': 3,\n",
    "  'sigma': 1,\n",
    "  'units': 'pixels',\n",
    "  'normalize': True,\n",
    "})\n",
    "\n",
    "# Compute a difference-of-Gaussians (DOG) kernel.\n",
    "dog = fat.add(skinny)\n",
    "\n",
    "# Compute the zero crossings of the second derivative, display.\n",
    "zeroXings = image.convolve(dog).zeroCrossing()\n",
    "Map.setCenter(-122.054, 37.7295, 10)\n",
    "Map.addLayer(zeroXings.updateMask(zeroXings), {'palette': 'FF0000'}, 'zero crossings')\n",
    "\n",
    "Map.addLayerControl()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The zero-crossings output for an area near the San Francisco, CA airport should look something like Figure 1."
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
